package com.szxb.facebus.task.work;

import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.szxb.facebus.BuildConfig;
import com.szxb.facebus.BusApp;
import com.szxb.facebus.base.BaseThread;
import com.szxb.facebus.db.entity.bean.BlackFaceListBean;
import com.szxb.facebus.db.entity.face.LineBlackFaceListEntity;
import com.szxb.facebus.db.entity.face.LineBlackFaceListEntityDao;
import com.szxb.facebus.db.entity.face.LineFaceListEntity;
import com.szxb.facebus.db.entity.face.LineFaceListEntityDao;
import com.szxb.facebus.db.entity.face.LineFaceRecordEntity;
import com.szxb.facebus.db.entity.face.LineFaceRecordEntityDao;
import com.szxb.facebus.db.entity.scan.ScanInfoEntity;
import com.szxb.facebus.db.manager.DBCore;
import com.szxb.facebus.db.manager.DBManager;
import com.szxb.facebus.net.ftp.FTPUtil;
import com.szxb.facebus.net.ftp.FtpResponse;
import com.szxb.facebus.net.http.JsonRequest;
import com.szxb.facebus.util.basics.Config;
import com.szxb.facebus.util.basics.Constant;
import com.szxb.facebus.util.basics.DateUtil;
import com.szxb.facebus.util.basics.HexUtil;
import com.szxb.facebus.util.basics.Utils;
import com.szxb.facebus.util.params.ParamsUtil;
import com.szxb.facebus.util.schedule.ThreadFactory;
import com.szxb.facebus.util.sign.ParamSingUtil;
import com.szxb.mlog.SLog;
import com.tencent.wlxsdk.WlxSdk;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SyncRequestExecutor;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作者：Tangren on 2018-12-10
 * 包名：com.szxb.facebus.task.service
 * 邮箱：996489865@qq.com
 * TODO:更新参数
 */

public class WorkThread extends BaseThread {

    public WorkThread(String name) {
        super(name);
    }

    private Object objectData;

    public WorkThread(String name, Object objectData) {
        super(name);
        this.objectData = objectData;
    }

    @Override
    public void runWork() {
        super.runWork();
        try {
            switch (getName()) {
                case Constant.UPDATE_LINE_FACE_LIST:
                    updateScanFaceIDList();
                    break;
                case Constant.UPDATE_LINE_BLACK_FACE_LIST:
                    updateScanBlackFaceIDList();
                    break;
                case Constant.SAVE_SCAN_FACE_RECORD:
                    LineFaceRecordEntity lineFaceRecordEntity = (LineFaceRecordEntity) objectData;
                    LineFaceRecordEntityDao dao = DBCore.getDaoSession().getLineFaceRecordEntityDao();
                    dao.insertOrReplace(lineFaceRecordEntity);
                    upUnFaceRecord(lineFaceRecordEntity);
                    break;
                case Constant.PUSH_SCAN_FACE_RECORDS:
                    upUnFaceRecordList();
                    break;
                case Constant.PUSH_SCAN_FACE_RECORD:
                    LineFaceRecordEntity faceRecordEntity = (LineFaceRecordEntity) objectData;
                    upUnFaceRecord(faceRecordEntity);
                    break;
                case Constant.WECHAT:
                    //保存微信交易
                    ScanInfoEntity infoEntity = (ScanInfoEntity) objectData;
                    DBCore.getDaoSession().getScanInfoEntityDao().insertOrReplaceInTx(infoEntity);
                    break;
                default:

                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            SLog.e("WorkThread(runWork.java:70)" + Utils.getExectionStr(e));
        }

    }

    private void updateScanFaceIDList() {
        FtpResponse response = new FTPUtil()
                .builder(BuildConfig.FTP_IP)
                .setPort(BuildConfig.FTP_PORT)
                .setLogin(BuildConfig.FTP_USER, BuildConfig.FTP_PSW)
                .setPath(Environment.getExternalStorageDirectory() + "/file/")
                .setFTPPath(BusApp.getPosManager().getAppId() + "/")
                .setForce(-1)
                .setTag("下载人脸列表文件")
                .download("FACE", BusApp.getPosManager().getLienNo());
        if (response.getIsOk() >= 0) {
//            ThreadFactory.getScheduledPool().stopTask(Constant.UPDATE_LINE_FACE_LIST);
            if (response.getIsOk() == FtpResponse.SUCCESSFUL) {
                File pathFile = new File(Environment.getExternalStorageDirectory() + "/file/" + response.getFileName());
                String faceListStr = HexUtil.readFileToString(pathFile);
                SLog.d("WorkThread(updateScanFaceIDList.java:120)" + faceListStr);
                String lineNo = BusApp.getPosManager().getLienNo();
                if (!TextUtils.isEmpty(faceListStr)) {
                    //更新人脸列表
                    try {
                        WlxSdk.updateIdList(faceListStr);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    List<LineFaceListEntity> faceList = new ArrayList<>();
                    JSONArray array = JSONArray.parseArray(faceListStr);
                    if (array == null || array.isEmpty()) {
                        return;
                    }
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        String cardId = object.getString("card_id");
                        String faceId = object.getString("face_id");
                        LineFaceListEntity faceEntity = new LineFaceListEntity();
                        faceEntity.setFaceID(faceId);
                        faceEntity.setCard_id(cardId);
                        faceEntity.setLineNo(lineNo);
                        faceEntity.setTime(DateUtil.getCurrentTime());
                        faceList.add(faceEntity);
                    }
                    LineFaceListEntityDao dao = DBCore.getDaoSession().getLineFaceListEntityDao();
                    dao.deleteAll();
                    dao.insertOrReplaceInTx(faceList);
                    SLog.d("BgTaskWorkThread(updateScanFaceIDList.java:83)人脸列表更新成功");
                }
            } else {
                SLog.d("BgTaskWorkThread(updateScanFaceIDList.java:96)" + response.getIsOk() + "," + response.getMsg());
            }
        }
    }

    private void updateScanBlackFaceIDList() {
        JsonRequest request = new JsonRequest(Config.URL_FACE_BLACK_LIST);
        request.set(ParamsUtil.getBlackList());
        Response<JSONObject> execute = SyncRequestExecutor.INSTANCE.execute(request);
        if (execute.isSucceed()) {
            ThreadFactory.getScheduledPool().stopTask(Constant.UPDATE_LINE_BLACK_FACE_LIST);
            BlackFaceListBean blackFaceListBean = new Gson().fromJson(execute.get().toJSONString(), BlackFaceListBean.class);
            if (blackFaceListBean.isOk()) {
                List<LineBlackFaceListEntity> list = blackFaceListBean.getList();
                LineBlackFaceListEntityDao lineBlackFaceListEntityDao = DBCore.getDaoSession().getLineBlackFaceListEntityDao();
                lineBlackFaceListEntityDao.deleteAll();
                lineBlackFaceListEntityDao.insertInTx(list);
                SLog.d("BgTaskWorkThread(updateScanBlackFaceIDList.java:111)人脸黑名单更新完成");
            } else {
                SLog.e("BgTaskWorkThread(updateScanBlackFaceIDList.java:114)人脸黑名单列表更新错误：" + blackFaceListBean.getResult());
            }
        } else {
            SLog.e("BgTaskWorkThread(updateScanBlackFaceIDList.java:115)" + execute.getException().toString());
        }
    }


    private void upUnFaceRecordList() {
        List<LineFaceRecordEntity> unLineFaceRecordList = DBManager.getUnLineFaceRecordList();
        if (unLineFaceRecordList.isEmpty()) {
            return;
        }
        for (LineFaceRecordEntity lineFaceRecordEntity : unLineFaceRecordList) {
            upUnFaceRecord(lineFaceRecordEntity);
            SystemClock.sleep(500);
        }

    }


    private void upUnFaceRecord(LineFaceRecordEntity lineFaceRecordEntity) {
        JsonRequest request = new JsonRequest(Config.URL_PUSH, RequestMethod.POST);
        request.set(getMap(lineFaceRecordEntity));
        Response<JSONObject> execute = SyncRequestExecutor.INSTANCE.execute(request);
        if (execute.isSucceed()) {
            JSONObject jsonObject = execute.get();
            if (jsonObject.containsKey("rescode") && jsonObject.getString("rescode").equals("0000")) {
                DBManager.updateFaceRecord(lineFaceRecordEntity, Constant.STATUS_REAL);
            }
        }
    }


    private Map<String, Object> getMap(LineFaceRecordEntity recordEntity) {
        String app_id = recordEntity.getApp_id();
        String timestamp = recordEntity.getTime();
        String biz_data_single = recordEntity.getBiz_data_single();
        Map<String, Object> map = ParamsUtil.commonMap(app_id, timestamp);
        map.put("app_id", BusApp.getPosManager().getAppId());
        map.put("sign", ParamSingUtil.getSign(app_id, timestamp, recordEntity.getBiz_data_single(), Config.private_key));
        map.put("biz_data", biz_data_single);
        return map;
    }
}
